import React, { useState, useEffect } from 'react';
import {
    Box,
    Typography,
    Grid,
    AppBar,
    Toolbar,
    IconButton,
    Menu,
    MenuItem,
    Button,
    Drawer,
    List,
    ListItem,
    ListItemIcon,
    ListItemText,
    ListItemButton,
    Avatar,
    Divider,
    useTheme,
    useMediaQuery,
    Paper,
    CircularProgress
} from '@mui/material';
import { styled } from '@mui/material/styles';
import {
    AccountCircle,
    Menu as MenuIcon,
    Logout as LogoutIcon,
    Dashboard as DashboardIcon,
    Settings as SettingsIcon,
    Folder as FolderIcon,
    Person as PersonIcon,
    AddBox as AddBoxIcon,
    ViewInAr as ViewInArIcon,
    Palette as PaletteIcon,
    Texture as TextureIcon,
    ChevronLeft as ChevronLeftIcon,
    ChevronRight as ChevronRightIcon
} from '@mui/icons-material';
import { motion } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { useModelContext } from '../contexts/ModelContext';
import NavigationService from '../components/NavigationService';

// 抽屉宽度
const drawerWidth = 240;

// 样式化的应用栏
const StyledAppBar = styled(AppBar, {
    shouldForwardProp: (prop) => prop !== 'open',
})(({ theme, open }) => ({
    zIndex: theme.zIndex.drawer + 1,
    transition: theme.transitions.create(['width', 'margin'], {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
    }),
    ...(open && {
        marginLeft: drawerWidth,
        width: `calc(100% - ${drawerWidth}px)`,
        transition: theme.transitions.create(['width', 'margin'], {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.enteringScreen,
        }),
    }),
}));

// 样式化的抽屉
const StyledDrawer = styled(Drawer, {
    shouldForwardProp: (prop) => prop !== 'open',
})(({ theme, open }) => ({
    '& .MuiDrawer-paper': {
        position: 'relative',
        whiteSpace: 'nowrap',
        width: drawerWidth,
        transition: theme.transitions.create('width', {
            easing: theme.transitions.easing.sharp,
            duration: theme.transitions.duration.enteringScreen,
        }),
        boxSizing: 'border-box',
        ...(!open && {
            overflowX: 'hidden',
            transition: theme.transitions.create('width', {
                easing: theme.transitions.easing.sharp,
                duration: theme.transitions.duration.leavingScreen,
            }),
            width: theme.spacing(7),
            [theme.breakpoints.up('sm')]: {
                width: theme.spacing(9),
            },
        }),
    },
}));

// 样式化的内容区域
const Main = styled('main', {
    shouldForwardProp: (prop) => prop !== 'open',
})(({ theme, open }) => ({
    flexGrow: 1,
    padding: theme.spacing(3),
    transition: theme.transitions.create('margin', {
        easing: theme.transitions.easing.sharp,
        duration: theme.transitions.duration.leavingScreen,
    }),
    marginLeft: `-${drawerWidth}px`,
    ...(open && {
        transition: theme.transitions.create('margin', {
            easing: theme.transitions.easing.easeOut,
            duration: theme.transitions.duration.enteringScreen,
        }),
        marginLeft: 0,
    }),
}));

// 样式化的统计卡片
const StyledStatCard = styled(Paper)(({ theme }) => ({
    padding: theme.spacing(3),
    borderRadius: 12,
    boxShadow: '0px 4px 20px rgba(0, 0, 0, 0.05)',
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    transition: 'all 0.3s ease',
    '&:hover': {
        transform: 'translateY(-5px)',
        boxShadow: '0px 10px 25px rgba(0, 0, 0, 0.1)',
    }
}));

// 统计卡片组件
const StatCard = ({ title, value, icon, color }) => {
    return (
        <StyledStatCard>
            <Box display="flex" alignItems="center" mb={2}>
                <Avatar sx={{ bgcolor: `${color}.100`, color: `${color}.800`, mr: 2 }}>
                    {icon}
                </Avatar>
                <Typography variant="h6" color="text.secondary">
                    {title}
                </Typography>
            </Box>
            <Typography variant="h4" fontWeight="bold">
                {value}
            </Typography>
        </StyledStatCard>
    );
};

// 将ViewInArIcon重命名为ModelIcon以匹配现有代码
const ModelIcon = ViewInArIcon;

const Dashboard = () => {
    const theme = useTheme();
    const isMobile = useMediaQuery(theme.breakpoints.down('md'));
    const { currentUser, logout } = useAuth();
    const { models, loading } = useModelContext();
    const navigate = useNavigate();

    // 菜单状态
    const [anchorEl, setAnchorEl] = useState(null);
    const [drawerOpen, setDrawerOpen] = useState(!isMobile);

    // 在组件加载时获取模型
    useEffect(() => {
        // fetchModels(); // 移除这行，因为ModelContext中已经在初始化时调用了fetchModels
    }, []);  // 移除fetchModels依赖

    // 处理抽屉开关
    const toggleDrawer = () => {
        setDrawerOpen(!drawerOpen);
    };

    // 处理用户菜单
    const handleProfileMenuOpen = (event) => {
        setAnchorEl(event.currentTarget);
    };

    const handleMenuClose = () => {
        setAnchorEl(null);
    };

    // 处理登出
    const handleLogout = () => {
        logout();
        navigate('/login');
    };

    // 处理创建新模型
    const handleCreateModel = () => {
        navigate('/models/geometry/create');
    };

    // 菜单是否打开
    const isMenuOpen = Boolean(anchorEl);

    // 用户菜单
    const renderMenu = (
        <Menu
            anchorEl={anchorEl}
            anchorOrigin={{
                vertical: 'bottom',
                horizontal: 'right',
            }}
            id="primary-account-menu"
            keepMounted
            transformOrigin={{
                vertical: 'top',
                horizontal: 'right',
            }}
            open={isMenuOpen}
            onClose={handleMenuClose}
        >
            <MenuItem onClick={handleMenuClose}>
                <PersonIcon fontSize="small" sx={{ mr: 1 }} />
                个人资料
            </MenuItem>
            <MenuItem onClick={handleMenuClose}>
                <SettingsIcon fontSize="small" sx={{ mr: 1 }} />
                设置
            </MenuItem>
            <Divider />
            <MenuItem onClick={handleLogout}>
                <LogoutIcon fontSize="small" sx={{ mr: 1 }} />
                退出登录
            </MenuItem>
        </Menu>
    );

    // 处理菜单项点击
    const handleMenuItemClick = (path) => {
        if (path === '/textures') {
            // 使用自定义的导航服务跳转到材料库
            console.log('点击材料库菜单项，准备导航到:', path);
            NavigationService.goToMaterialLibrary();
            console.log('导航服务已调用，当前哈希:', window.location.hash);

            // 强制刷新以确保组件重新渲染
            setTimeout(() => {
                console.log('延迟后的哈希值:', window.location.hash);
                if (window.location.hash === '#textures') {
                    window.dispatchEvent(new HashChangeEvent('hashchange'));
                    console.log('手动触发hashchange事件');
                }
            }, 100);
        } else {
            // 其他页面使用常规导航
            navigate(path);
        }
    };

    // 侧边栏菜单项
    const menuItems = [
        { text: '概览', icon: <DashboardIcon />, path: '/' },
        { text: '我的模型', icon: <ModelIcon />, path: '/models' },
        { text: '新建模型', icon: <AddBoxIcon />, path: '/models/geometry/create' },
        {
            text: '材料库',
            icon: <TextureIcon />,
            path: '/textures',
            onClick: () => {
                console.log('点击材料库菜单项，准备导航到材料库页面');
                navigate('/textures');
                return false; // 阻止原生导航
            }
        },
        { text: '颜色方案', icon: <PaletteIcon />, path: '/colors' },
        { text: '文件管理', icon: <FolderIcon />, path: '/files' },
    ];

    return (
        <Box sx={{ display: 'flex', height: '100vh' }}>
            {/* 应用栏 */}
            <StyledAppBar position="fixed" open={drawerOpen}>
                <Toolbar>
                    <IconButton
                        edge="start"
                        color="inherit"
                        aria-label="open drawer"
                        onClick={toggleDrawer}
                        sx={{
                            marginRight: 2,
                            ...(drawerOpen && !isMobile && { display: 'none' }),
                        }}
                    >
                        <MenuIcon />
                    </IconButton>
                    <ModelIcon sx={{ display: { xs: 'none', md: 'flex' }, mr: 1 }} />
                    <Typography
                        variant="h6"
                        noWrap
                        component="div"
                        sx={{ flexGrow: 1 }}
                    >
                        3D建模系统
                    </Typography>

                    <Box sx={{ display: 'flex', alignItems: 'center' }}>
                        <Typography variant="body2" sx={{ mr: 2, display: { xs: 'none', sm: 'block' } }}>
                            欢迎, {currentUser?.username || '用户'}
                        </Typography>
                        <IconButton
                            size="large"
                            edge="end"
                            aria-label="account of current user"
                            aria-controls="primary-account-menu"
                            aria-haspopup="true"
                            onClick={handleProfileMenuOpen}
                            color="inherit"
                        >
                            <AccountCircle />
                        </IconButton>
                    </Box>
                </Toolbar>
            </StyledAppBar>
            {renderMenu}

            {/* 侧边抽屉 */}
            <StyledDrawer
                variant={isMobile ? "temporary" : "permanent"}
                open={drawerOpen}
                onClose={isMobile ? toggleDrawer : undefined}
            >
                <Toolbar
                    sx={{
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'flex-end',
                        px: [1],
                    }}
                >
                    <IconButton onClick={toggleDrawer}>
                        {theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
                    </IconButton>
                </Toolbar>
                <Divider />
                <List component="nav">
                    {menuItems.map((item, index) => (
                        <ListItem key={item.text} disablePadding>
                            <ListItemButton
                                sx={{
                                    minHeight: 48,
                                    justifyContent: drawerOpen ? 'initial' : 'center',
                                    px: 2.5,
                                }}
                                onClick={() => {
                                    // 如果有自定义onClick函数，优先使用
                                    if (item.onClick) {
                                        const shouldContinue = item.onClick();
                                        if (shouldContinue === false) {
                                            console.log('自定义点击处理程序阻止了默认导航');
                                            return;
                                        }
                                    }

                                    // 否则使用默认导航处理
                                    console.log('使用默认导航处理:', item.path);
                                    handleMenuItemClick(item.path)
                                }}
                            >
                                <ListItemIcon
                                    sx={{
                                        minWidth: 0,
                                        mr: drawerOpen ? 3 : 'auto',
                                        justifyContent: 'center',
                                    }}
                                >
                                    {item.icon}
                                </ListItemIcon>
                                <ListItemText
                                    primary={item.text}
                                    sx={{
                                        opacity: drawerOpen ? 1 : 0,
                                        display: !drawerOpen ? 'none' : 'block'
                                    }}
                                />
                            </ListItemButton>
                        </ListItem>
                    ))}
                </List>
            </StyledDrawer>

            {/* 主内容区域 */}
            <Main open={drawerOpen && !isMobile}>
                <Toolbar /> {/* 这个Toolbar是为了与AppBar对齐，保持空间 */}

                <Box component={motion.div}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5 }}
                >
                    <Typography variant="h4" component="h1" gutterBottom sx={{ fontWeight: 'bold', mb: 4 }}>
                        概览
                    </Typography>

                    {/* 统计卡片 */}
                    <Grid container spacing={3} sx={{ mb: 4 }}>
                        <Grid item xs={12} sm={6} md={3}>
                            <StatCard
                                title="模型总数"
                                value={models?.length || 0}
                                icon={<ModelIcon />}
                                color="primary"
                            />
                        </Grid>
                        <Grid item xs={12} sm={6} md={3}>
                            <StatCard
                                title="近期编辑"
                                value={models?.filter(m => new Date(m.createdAt) > new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)).length || 0}
                                icon={<ModelIcon />}
                                color="secondary"
                            />
                        </Grid>
                        <Grid item xs={12} sm={6} md={3}>
                            <StatCard
                                title="材质数量"
                                value="36"
                                icon={<TextureIcon />}
                                color="success"
                            />
                        </Grid>
                        <Grid item xs={12} sm={6} md={3}>
                            <StatCard
                                title="协作项目"
                                value="5"
                                icon={<PaletteIcon />}
                                color="info"
                            />
                        </Grid>
                    </Grid>

                    {/* 最近项目 */}
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                        <Typography variant="h5" gutterBottom sx={{ mt: 5, fontWeight: 600 }}>
                            最近模型
                        </Typography>
                        <Button
                            variant="outlined"
                            size="small"
                            onClick={() => navigate('/models')}
                        >
                            查看全部
                        </Button>
                    </Box>

                    {loading ? (
                        <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
                            <CircularProgress />
                        </Box>
                    ) : (
                        <Grid container spacing={3}>
                            {models && models.length > 0 ? (
                                models.slice(0, 6).map((model) => (
                                    <Grid item xs={12} sm={6} md={4} lg={3} key={model.id}>
                                        <Paper
                                            component={motion.div}
                                            whileHover={{ y: -10, boxShadow: "0 20px 30px rgba(0,0,0,0.1)" }}
                                            sx={{
                                                p: 0,
                                                borderRadius: 2,
                                                overflow: 'hidden',
                                                height: 200,
                                                position: 'relative',
                                                cursor: 'pointer',
                                                bgcolor: 'grey.100'
                                            }}
                                            onClick={() => navigate(`/models/edit/${model.id}`)}
                                        >
                                            <Box
                                                sx={{
                                                    height: '100%',
                                                    display: 'flex',
                                                    alignItems: 'center',
                                                    justifyContent: 'center',
                                                    backgroundImage: `url(https://source.unsplash.com/random/300x200/?3d,model&sig=${model.id})`,
                                                    backgroundSize: 'cover',
                                                    backgroundPosition: 'center'
                                                }}
                                            >
                                                <Box sx={{
                                                    position: 'absolute',
                                                    top: 0,
                                                    left: 0,
                                                    right: 0,
                                                    bottom: 0,
                                                    bgcolor: 'rgba(0,0,0,0.2)'
                                                }} />
                                            </Box>
                                            <Box
                                                sx={{
                                                    position: 'absolute',
                                                    bottom: 0,
                                                    left: 0,
                                                    right: 0,
                                                    p: 2,
                                                    bgcolor: 'rgba(255,255,255,0.9)',
                                                    borderTop: '1px solid rgba(0,0,0,0.05)'
                                                }}
                                            >
                                                <Typography variant="subtitle1" fontWeight="bold">
                                                    {model.name}
                                                </Typography>
                                                <Typography variant="body2" color="text.secondary">
                                                    最后编辑: {new Date(model.createdAt).toLocaleDateString('zh-CN')}
                                                </Typography>
                                            </Box>
                                        </Paper>
                                    </Grid>
                                ))
                            ) : (
                                <Grid item xs={12}>
                                    <Paper
                                        elevation={0}
                                        sx={{
                                            py: 6,
                                            textAlign: 'center',
                                            backgroundColor: 'rgba(0, 0, 0, 0.02)',
                                            borderRadius: 2
                                        }}
                                    >
                                        <Typography variant="h6" color="text.secondary" gutterBottom>
                                            您还没有创建任何模型
                                        </Typography>
                                        <Button
                                            variant="contained"
                                            color="primary"
                                            startIcon={<AddBoxIcon />}
                                            onClick={handleCreateModel}
                                            sx={{ mt: 2 }}
                                        >
                                            创建您的第一个模型
                                        </Button>
                                    </Paper>
                                </Grid>
                            )}
                        </Grid>
                    )}

                    {/* 创建新项目按钮 */}
                    <Box sx={{ display: 'flex', justifyContent: 'center', mt: 5 }}>
                        <Button
                            variant="contained"
                            color="primary"
                            size="large"
                            startIcon={<AddBoxIcon />}
                            component={motion.button}
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                            onClick={handleCreateModel}
                        >
                            创建新模型
                        </Button>
                    </Box>
                </Box>
            </Main>
        </Box>
    );
};

export default Dashboard;